package presenter.rename;

import main.InputBean;
import utils.FileBean;
import presenter.record.IRecorder;
import utils.TextUtils;

import java.util.Map;

/**
 * GoPro文件的重命名,因为GoPro的命名会打乱文件夹的显示,导致看的很奇怪的排序
 * <p>
 * GH010151.MP4
 * GH,GX 01(正常的) 02(要修改) 03(要修改) 11(要修改)
 */
public class GoProRecorderImpl implements IReNamer {
    private static final String DEFAULT_INDEX = "01";

    @Override
    public boolean needReName(InputBean info, FileBean bean) {
        String name = bean.name();
        String PRE_FIX_GH = "GH01";
        String PRE_FIX_GX = "GX01";
        return !TextUtils.isEmpty(name)
                && (name.startsWith("GH") || name.startsWith("GX"))
                && !name.startsWith(PRE_FIX_GH)
                && !name.startsWith(PRE_FIX_GX);
    }

    @Override
    public void reName(InputBean info,FileBean bean, Map<String, String> pairs) {
        String name = bean.name();
        String fileIndex = fileIndex(name);                                 // GH020151.MP4 -> 02
        String sourceName = name.replaceFirst(fileIndex, DEFAULT_INDEX);    // GH020151.MP4 -> GH010151.MP4
        String toName = insertedIndex(sourceName, fileIndex);               // GH010151.MP4 -> GH010151-02.MP4
        String firstFileName = insertedIndex(sourceName, DEFAULT_INDEX);    // GH010151.MP4 -> GH010151-01.MP4

        pairs.put(fixPath(bean, name), fixPath(bean, toName));
        pairs.put(fixPath(bean, sourceName), fixPath(bean, firstFileName));
    }

    private String fixPath(FileBean bean, String name) {
        return IRecorder.fixedPath(bean.parent(), name);
    }

    //插入序号，比如-01，-02，-03
    private String insertedIndex(String name, String index) {
        String[] split = name.split("\\.");
        return String.format("%s-%s.%s", split[0], index, split[1]);
    }

    private String fileIndex(String name) {
        return String.valueOf(name.charAt(2)) + name.charAt(3);
    }
}
